package com.progscala.swap

import scala.collection.mutable.Map

object ChecksumAccumulator {
  
  private val cache = Map[String, Int]()
  
  def calculate(s: String): Int = 
    if (cache.contains(s)) {
      cache(s)
    } else {
       val acc = new ChecksumAccumulator
       for (c <- s)
         acc.add(c.toByte)
       val cs = acc.checksum()
       cache += (s -> cs)
       cs
    }
  
  def main(args: Array[String]) {
    val rst = ChecksumAccumulator.calculate("sss");
    Console.println(rst)
    val csa = new ChecksumAccumulator
    Console.println(csa.calculate("good"));
  }
  
}

class ChecksumAccumulator {
  private var sum = 0
  def add(b: Byte) { sum += b }
  def checksum(): Int = ~(sum &0xFF) + 1
  
  def calculate(s: String): Int = 
    ChecksumAccumulator.calculate(s)
}